package com.scheduler.starter;

import cn.hutool.core.util.StrUtil;
import com.scheduler.servicediscover.MysqlServiceDiscoverRegistrationCenter;
import com.scheduler.servicediscover.ServiceDiscoverHeartbeat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class SchedulerCenterStartBySpring implements ApplicationContextAware, SmartApplicationListener {

    @Value("${scheduler.server.ipPrefix:}")
    private String ipPrefix;

    @Value("${scheduler.server.group:default}")
    private String serverGroup;


    @Value("${scheduler.server.port:7080}")
    private int serverPort;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationContextEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    public static final AtomicBoolean initialized = new AtomicBoolean(false);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (initialized.compareAndSet(false, true)) {
            log.info("初始化调度中心开始");
            initServiceDiscover();
            log.info("初始化调度中心完成");
        }
    }

    /**
     * 启动服务发现
     */
    private void initServiceDiscover() {
        if (StrUtil.isNotBlank(ipPrefix)) {
            ServiceDiscoverHeartbeat.INSTANCE.setIpPrefix(ipPrefix);
        }
        ServiceDiscoverHeartbeat.INSTANCE.setPort(serverPort);
        ServiceDiscoverHeartbeat.INSTANCE.setServiceDiscoverRegistrationCenter(new MysqlServiceDiscoverRegistrationCenter(applicationContext, serverGroup));
        ServiceDiscoverHeartbeat.INSTANCE.start();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
